package com.jet.rtdb.socket.client.netty;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jet.rtdb.pojo.QueryLastData;
import com.jet.rtdb.pojo.QueryLastDataList;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.io.UnsupportedEncodingException;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: zhangkaifeng.
 * @CreateTime: 2017/8/17 15:46
 * @Description:
 */


public class RtdbClientHandler extends ChannelInboundHandlerAdapter {

    protected static ChannelHandlerContext channelHandlerContext;

    private static QueryLastDataList electric;
    private final static Lock lock = new ReentrantLock();
    private final static Condition condition = lock.newCondition();


    private GsonBuilder gsonbuilder = new GsonBuilder().serializeNulls();
    private Gson gson = gsonbuilder.create();

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        lock.lock();
        ByteBuf in = (ByteBuf) msg;
        try {
            byte type = in.readByte();
            int length = in.readInt();
            ByteBuf buf = in.readBytes(length);
            byte[] req = new byte[buf.readableBytes()];
            buf.readBytes(req);
            String responseMessage = new String(req, "UTF-8");
            electric = this.gson.fromJson(responseMessage, QueryLastDataList.class);
            condition.signal();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } finally {
            ctx.close();
            in.release();
            lock.unlock();
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        channelHandlerContext = ctx;

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

    public void getLastData() {
        QueryLastData queryLastData = new QueryLastData("w3.ryxbdt", "RYXBDT001_RYXBDT1-1-1_P");
        QueryLastDataList queryLastDatas = new QueryLastDataList();
        queryLastDatas.add(queryLastData);
        channelHandlerContext.writeAndFlush(queryLastDatas);
        lock.lock();
        try {
            condition.await();
            System.out.println(electric);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
